package com.lagou.handler;

import com.lagou.protocol.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.BeansException;
import org.springframework.cglib.reflect.FastClass;
import org.springframework.cglib.reflect.FastMethod;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;

/**
 * 自定义的业务处理器
 */
@Component
public class UserServiceHandler extends ChannelInboundHandlerAdapter implements ApplicationContextAware {

    private static ApplicationContext applicationContext2;
    //当客户端读取数据时,该方法会被调用
    //此处我理解错误，不是客户端一写完，channelRead 就会被调用，是要客户读取数据时，该方法才会调用
    //所以要向客户端channel 里写数据，然后客户端才能来读
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        RpcRequest rpcRequest = (RpcRequest) msg;
        handler(rpcRequest);
        ctx.writeAndFlush("success");


    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        UserServiceHandler.applicationContext2 = applicationContext ;
    }

    private Object handler(RpcRequest rpcRequest) throws ClassNotFoundException, InvocationTargetException {

        //使用Class.forName 进行加载Class 文件
        Class<?> clazz = Class.forName(rpcRequest.getClassName());
        Object serviceBean = applicationContext2.getBean(clazz);

        Class<?> serviceClass = serviceBean.getClass();

        String methodName = rpcRequest.getMethodName();

        Class<?>[] parameterTypes = rpcRequest.getParameterTypes();
        Object[] parameters = rpcRequest.getParameters();
        // 通过cglib 调用方法
        FastClass fastClass = FastClass.create(serviceClass);
        FastMethod fastMethod = fastClass.getMethod(methodName,parameterTypes);


        return fastMethod.invoke(serviceBean,parameters);
    }
}
